package cn.lg.soar.common.util;

import cn.lg.soar.common.util.reflect.ReflectUtil;
import org.springframework.util.CollectionUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @author luguoxiang
 * @date 2022/5/30
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface UrlUtils {

    /**
     * 处理url参数
     * @param params
     * @return
     */
    static String handlerParams(Object params) {
        if (params == null) {
            return "";
        }
        StringJoiner joiner = new StringJoiner("&");
        ReflectUtil.scanField(params.getClass(), field -> {
            Object value = ReflectUtil.get(params, field);
            if (value != null) {
                String encodedValue;
                try {
                    encodedValue = URLEncoder.encode(value.toString(), StandardCharsets.UTF_8);
                } catch (Exception e) {
                    encodedValue = value.toString();
                }
                joiner.add(field.getName() + "=" + encodedValue);
            }
        });
        return joiner.toString();
    }

    /**
     * 处理url参数
     * @param params
     * @return
     */
    static String handlerParams(Map<String, ?> params) {
        if (CollectionUtils.isEmpty(params)) {
            return "";
        }
        StringJoiner joiner = new StringJoiner("&");
        params.forEach((key, value) -> {
            if (value != null) {
                String encodedValue = URLEncoder.encode(value.toString(), StandardCharsets.UTF_8);
                joiner.add(key + "=" + encodedValue);
            }
        });
        return joiner.toString();
    }

    /**
     * 处理url参数
     * @param url
     * @param params
     * @return
     */
    static String handlerParams(String url, Object params) {
        if (params == null) {
            return url;
        }
        return url + (url.contains("?") ? '&' : '?') + handlerParams(params);
    }

    /**
     * 处理url参数
     * @param url
     * @param params
     * @return
     */
    static String handlerParams(String url, Map<String, ?> params) {
        if (CollectionUtils.isEmpty(params)) {
            return url;
        }
        return url + (url.contains("?") ? '&' : '?') + handlerParams(params);
    }

}
